const sequelize = require('../config/database')

async function fixProductsTable() {
  try {
    console.log('开始修复products表结构...')
    
    // 测试数据库连接
    await sequelize.authenticate()
    console.log('数据库连接成功')
    
    // 检查表是否存在
    const [results] = await sequelize.query("SHOW TABLES LIKE 'products'")
    if (results.length === 0) {
      console.log('products表不存在，需要创建')
      return false
    }
    
    // 检查现有字段
    const [columns] = await sequelize.query("DESCRIBE products")
    const existingColumns = columns.map(col => col.Field)
    console.log('现有字段:', existingColumns)
    
    // 需要添加的字段
    const requiredFields = [
      'paper_size',
      'paper_type', 
      'color_type',
      'stock_warning',
      'is_new',
      'is_hot'
    ]
    
    // 检查并添加缺失的字段
    for (const field of requiredFields) {
      if (!existingColumns.includes(field)) {
        console.log(`添加字段: ${field}`)
        
        switch (field) {
          case 'paper_size':
            await sequelize.query(`
              ALTER TABLE products 
              ADD COLUMN paper_size ENUM('A4', 'A3', 'A5', 'other') NULL COMMENT '纸张尺寸'
            `)
            break
            
          case 'paper_type':
            await sequelize.query(`
              ALTER TABLE products 
              ADD COLUMN paper_type VARCHAR(50) NULL COMMENT '纸张类型'
            `)
            break
            
          case 'color_type':
            await sequelize.query(`
              ALTER TABLE products 
              ADD COLUMN color_type ENUM('bw', 'color', 'both') NULL DEFAULT 'bw' COMMENT '颜色类型'
            `)
            break
            
          case 'stock_warning':
            await sequelize.query(`
              ALTER TABLE products 
              ADD COLUMN stock_warning INT NULL DEFAULT 100 COMMENT '库存预警值'
            `)
            break
            
          case 'is_new':
            await sequelize.query(`
              ALTER TABLE products 
              ADD COLUMN is_new TINYINT NOT NULL DEFAULT 0 COMMENT '是否新品'
            `)
            break
            
          case 'is_hot':
            // 检查是否已存在但类型不对
            if (existingColumns.includes('is_hot')) {
              await sequelize.query(`
                ALTER TABLE products 
                MODIFY COLUMN is_hot TINYINT NOT NULL DEFAULT 0 COMMENT '是否热门'
              `)
            } else {
              await sequelize.query(`
                ALTER TABLE products 
                ADD COLUMN is_hot TINYINT NOT NULL DEFAULT 0 COMMENT '是否热门'
              `)
            }
            break
        }
      }
    }
    
    // 检查image_url字段是否存在
    if (!existingColumns.includes('image_url')) {
      console.log('添加字段: image_url')
      await sequelize.query(`
        ALTER TABLE products 
        ADD COLUMN image_url VARCHAR(500) NULL COMMENT '商品图片'
      `)
    }
    
    console.log('products表结构修复完成!')
    return true
    
  } catch (error) {
    console.error('修复products表失败:', error)
    throw error
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  fixProductsTable().finally(() => {
    sequelize.close()
  })
}

module.exports = { fixProductsTable }